import useAuthStore from '@/stores/auth'
import baseUserHttp from '@/apis/user/BaseUserHttp'
class BaseAliOssHttp {
    constructor() {
        this.baseUrl = import.meta.env.VITE_BASE_USER_URL + '/user'
        this.aliOssDomain = import.meta.env.VITE_BASE_ALIOSS_DOMAIN
        this.bucketName = import.meta.env.VITE_BASE_ALIOSS_BUCKET_NAME
        this.region = import.meta.env.VITE_BASE_ALIOSS_REGION
    }
    _build_download_sign_url(object_name) {
        pass
    }
    _build_upload_sign_url(object_name) {
        pass
    }

    _fetch_upload_presigned=async(file_extension,expires=3600)=>{
        const authStore = useAuthStore()
        const url=this.baseUrl + '/upload/presigned'
        const response=await uni.request({
            url: url,
            method: 'GET',
            data: {
                file_extension,
                expires
            },
            header:{
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + authStore.access_token
            }
        })
        if (response.statusCode === 200) {
            return response.data
        }else if (response.statusCode === 403) {
            await baseUserHttp.refreshToken()
            return this.fetch_upload_presigned(file_extension,expires)
        }else{
            uni.showToast({
                title: response.data.detail,
                icon: 'none'
            })
        }
    }
    _fetch_sts_token=async ()=>{
        const authStore = useAuthStore()
        const url=this.baseUrl + '/sts_token'
        const response=await uni.request({
            url: url,
            method: 'GET',
            header:{
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + authStore.access_token
            }
        })
        if (response.statusCode === 200) {
            return response.data
        }else if (response.statusCode === 403) {
            await baseUserHttp.refreshToken()
            return this._fetch_sts_token()
        }else{
            uni.showToast({
                title: response.data.detail,
                icon: 'none'
            })
        }
    }

}

async function get_upload_presigned(file_extension,expires=3600){
    const baseAliOssHttp = new BaseAliOssHttp()
    const presigned=await baseAliOssHttp._fetch_upload_presigned(file_extension,expires)
    return presigned
}
async function upload_file_to_oss(file_path,params){
    const presigned=await get_upload_presigned(object_name)
}

async function get_sts_token(){
    const baseAliOssHttp = new BaseAliOssHttp()
    const token=await baseAliOssHttp._fetch_sts_token()
    return token
}

export default {
    get_upload_presigned,
    upload_file_to_oss,
    get_sts_token
}
